package org.iabako.server.dao.business;

import org.iabako.server.dao.JpaDAO;
import org.iabako.shared.entity.business.PaymentRequestConfig;
import org.iabako.shared.entity.user.Enterprise;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by jose on 29/01/15.
 */

@Repository("paymentRequestDAO")
public class PaymentRequestDAO extends JpaDAO<Long, PaymentRequestDAO> {

    @Override
    protected String getUniqueNumberVerificationQuery() {
        return null;
    }

    @Override
    protected String getLastNumberQuery() {
        return null;
    }

    public PaymentRequestConfig getPaymentRequestConfig() {
        Enterprise enterprise = getSessionUser().getEnterprise();
        enterprise = enterprise.getParentEnterprise() == null ? enterprise : enterprise.getParentEnterprise();
        return getPaymentRequestConfigByEnterprise(enterprise);
    }

    public List<PaymentRequestConfig> getActivePaymentRequestList(List<Enterprise> activeEnterprises) {
        String query = "SELECT p FROM PaymentRequestConfig p JOIN p.enterprise e " +
                "WHERE p.daysBeforePayment >= 0 OR p.daysAfterPayment >=0 " +
                "AND e IN (:activeEnterprises)";
        return (List<PaymentRequestConfig>) entityManager.createQuery(query)
                .setParameter("activeEnterprises", activeEnterprises).getResultList();
    }

    public PaymentRequestConfig getPaymentRequestConfigByEnterprise(Enterprise enterprise) {
        String query = "SELECT MAX(p) FROM PaymentRequestConfig p WHERE enterprise = :enterprise";
        List<PaymentRequestConfig> list = (List<PaymentRequestConfig>) entityManager.createQuery(query).
                setParameter("enterprise", enterprise).getResultList();

        return list != null && list.size() > 0 ? list.get(0) : null;
    }
}
